import React, { CSSProperties, useEffect, useState } from 'react';
import { Statistic } from 'antd';
import { Layout, udp, useAsyncEffect, useRefreshList } from '@cscec/udp-ui';
import { PortalTitle, containerStyle } from '../common';

/**
 * 一体化资源平台汇总
 */
export default function ResourceCustomCount(props: IProps) {
  const {
    urlPath,
    urlParams,
    showGroup,
    showList,
    pathList,
    style,
    env,
  } = props;

  const [state, setState] = useState({
    content: [],
    groupData: [],
  });

  const [forceUpdate, setForceUpdate] = useState({});

  useAsyncEffect(async () => {
    const { status, data } = await env.fetcher({
      url: '/irp-api/irp-business-core/statistics/homeDashboard',
    });
    if (status === 0) {
      setState((p) => ({ ...p, groupData: data }));
    }
  }, [forceUpdate]);

  useRefreshList(() => {
    setForceUpdate({});
  }, 'MyWorkFlowTask');

  useEffect(() => {
    if (!showGroup || !state.groupData || state.groupData.length === 0) {
      return;
    }

    const groupInfo: any = state.groupData
      .find((value: any) => value.group === showGroup);
    if (!groupInfo || !groupInfo.items || groupInfo.items.length === 0) {
      return;
    }

    let content: any = [];
    if (showList && showList.length > 0) {
      showList.forEach((name) => {
        const itemData = groupInfo.items.find((element: any) => element.name === name.trim());
        if (itemData) {
          content.push(itemData);
        }
      });
    } else {
      content = groupInfo.items;
    }

    setState({ content });
  }, [showGroup, showList, state.groupData]);

  const handleClick = () => {
    if (urlPath && urlPath.length > 0) {
      try {
        udp.open(urlPath, JSON.parse(urlParams));
      } catch (err) {
        console.error(err);
      }
    }
  };

  return (
    <div style={{ ...containerStyle, ...style, pointerEvents: 'auto', marginBottom: '15px' }}>
      <div
        style={{ cursor: (urlPath && urlPath.length > 0) ? 'pointer' : 'default' }}
        onClick={handleClick}
      >
        <PortalTitle>{showGroup || ''}</PortalTitle>
      </div>
      <Layout
        direction="row"
        style={{
          marginTop: 24,
          gap: 24,
        }}
      >
        {state.content && state.content.map((groupItem: any, index: number) => {
          const { name = '', value = 0 } = groupItem;
          let hasPath = false;
          let pathParams: any = [];
          if (pathList.length > index) {
            pathParams = pathList[index];
            if (pathParams && pathParams.length > 0) {
              hasPath = true;
            }
          }
          return (
            <Layout.Flex key={name}>
              <div
                style={{ cursor: hasPath ? 'pointer' : 'default' }}
                onClick={() => {
                  if (!hasPath) {
                    return;
                  }

                  try {
                    const pathJson = JSON.parse(pathParams);
                    const { path } = pathJson || {};
                    if (path && path.length > 0) {
                      delete pathJson.path;
                      udp.open(path, pathJson);
                    }
                  } catch (err) {
                    console.error(err);
                  }
                }}
              >
                <Statistic title={name} value={value} />
              </div>
            </Layout.Flex>
          );
        })}
      </Layout>
    </div>
  );
}

export interface IProps {
  urlPath: string;
  urlParams: string;
  showGroup: string;
  showList: Array<string>;
  pathList: Array<string>;
  style?: CSSProperties;

  [x: string]: any;
}
